package com.deer.wms.base.system.web.zhBusiness.electricBox;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.deer.wms.base.system.dao.zh.electricBox.ElectricBoxItemMapper;
import com.deer.wms.base.system.model.ware.SupplierDto;
import com.deer.wms.base.system.model.zh.ElectricBoxDetail;
import com.deer.wms.base.system.service.box.IBoxItemService;
import com.deer.wms.base.system.service.zh.ElectricBoxItemService;
import com.deer.wms.common.core.controller.BaseController;
import com.deer.wms.common.core.domain.AjaxResult;
import com.deer.wms.common.core.page.TableDataInfo;
import com.deer.wms.common.utils.StringUtils;
import com.deer.wms.common.utils.poi.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/electricBox")
//@WebService(name = "WmsWebService")
public class ElectricBoxController extends BaseController {

    private ElectricBox electricBox;
    private ElectricBoxHead electricBoxHead;
    private ElectricBoxItem electricBoxItem;
    private List<ElectricBoxItem> electricBoxItemList;
    static Log log = LogFactory.get(ElectricBoxController.class);

    String prefix = "electricbox/";

    @Autowired
    private IBoxItemService iBoxItemService;
    @Autowired
    ElectricBoxItemService electricBoxItemService;
    @Autowired
    ElectricBoxItemMapper electricBoxItemMapper;

    @RequestMapping("selectFirm")
    @ResponseBody
    public TableDataInfo firm(SupplierDto supplier){
        PageHelper.startPage(supplier.getPageNum(),supplier.getPageSize());
        List<SupplierDto> list = electricBoxItemMapper.selectFirm(supplier);
        return getDataTable(list);
        //return list;
    }

    //导入
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<ElectricBoxDetail> util = new ExcelUtil<ElectricBoxDetail>(ElectricBoxDetail.class);
        List<ElectricBoxDetail> List = util.importExcel(file.getInputStream());

       // java.util.List<ElectricBoxDetail> electricBoxDetails = List.subList(2, List.size());
        for (ElectricBoxDetail e : List) {

            if (e.getTorrNumber() instanceof Integer) {
                if (StringUtils.isEmpty(e.getTorr())){
                    log.error("导入的电子箱单的Excel中，存在托号为空的数据,已跳过");
                    continue;
                }

                String outData = e.getOutData();
                if(outData!=null && outData!=""&& !outData.matches("^\\d{4}\\-(0?[1-9]|1[012])\\-(0?[1-9]|[12][0-9]|3[01])$")){
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
                    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
                    Date parse = sdf.parse(outData);
                    String format = sdf2.format(parse);
                    e.setOutData(format);
                }

                electricBoxItemService.InsertElectricBoxItem(e);
            }

        }
        return AjaxResult.success("导入成功");
    }

    //模板
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        List<ElectricBoxDetail> all = new ArrayList<>();
        ElectricBoxDetail e = new ElectricBoxDetail();
        e.setTorr("ZS9BH210514137").setAbnormalLength("0").setAbnormalLengthTheory("0")
                .setAbnormalSize("0").setB_Long("0").setBarCode("F02000007340")
                .setCoding("E2105D6414030300").setConductive("0080045787")
                .setCustomerProfile("UA+").setD_Location("0").setD_Long(216)
                .setDopant("0").setF_Beige("0").setF_Degree("C215150027")
                .setFirm("1021").setFlaw("2").setInclined("0").setInType("无")
                .setJ_Beige("0").setLengthInStorage("0").setNotGrind("0").setOutData("2021-05-15")
                .setP_Type("0").setPassivation_T("0").setR_Long(215).setRemark("二拼801拼缝宽2mm")
                .setScar("0").setScratch("0").setSize("295×210").setSizeType("0").setStria("0")
                .setT_Weigh("34.235").setTorrNumber(6756).setTotalLength("215").setTotalWeight("34.235")
                .setVerifyRemark("0").setWagonNumber("0").setWarehousing("0").setWeight("22.213")
                .setWorkShop("E2105D6414030300;G2105K73130W0000;");
        all.add(e);
        ExcelUtil<ElectricBoxDetail> util = new ExcelUtil<ElectricBoxDetail>(ElectricBoxDetail.class);
        return util.importTemplateExcel(all, "电子箱单导入模板");
    }

    /**
     * 导出列表
     */
    @RequiresPermissions("electricBox:export")
    @PostMapping("/export")
    @ResponseBody// <!--//导出全部 功能会造成内存溢出，不要使用-->
    public AjaxResult export(ElectricBoxDetail e) {
        List<ElectricBoxDetail> all = electricBoxItemService.selectAll(e);
        System.out.println(all);
        ExcelUtil<ElectricBoxDetail> util = new ExcelUtil<ElectricBoxDetail>(ElectricBoxDetail.class);
        return util.exportExcel(all, "电子箱单明细");
    }

    /**
     * 导出列表
     */
    @RequiresPermissions("electricBox:partExcel")
    @PostMapping("/partExcel")
    @ResponseBody
    public AjaxResult partExcel(@RequestParam String ids) {
        List<ElectricBoxDetail> byIds = electricBoxItemService.findByIds(ids);
        // List<BillInSapDto> billInSapList = billInSapService.findBillInSapDtoList(billInSapCriteria);
        ExcelUtil<ElectricBoxDetail> util = new ExcelUtil<ElectricBoxDetail>(ElectricBoxDetail.class);
        return util.exportExcel(byIds, "电子箱单明细");
    }

    @RequestMapping()
    public String view() {
        return prefix + "electricbox";
    }

    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo findBillInDetailListByBillId(ElectricBoxDetail e) {
        if (e.getFirm() != null && !e.getFirm().equals("")) {
            String[] split =e.getFirm().split(",");
            StringBuilder str = new StringBuilder();
            for (String s : split
            ) {
                str.append("'" + s + "',");
            }
            e.setFirm(str.toString().substring(0, str.length() - 1));
        }
        electricBoxItemService.updateItemLongRange();
        startPage();
        //System.out.println(e);
       // String firm = e.getFirm();
       // String substring = firm.substring(0, firm.length() );
      // e.setFirm(substring);
        List<ElectricBoxDetail> all = electricBoxItemService.selectAll(e);
        //System.out.println(all);
        return getDataTable(all);
    }

    /**
     * 修改电子箱单
     * @author 申紫微
     * @date 12:30 2021/7/18
     * @params id
     * @return java.lang.String
     **/
    @RequiresPermissions("electricBoxDetail:edit")
    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Integer id, ModelMap mmap){
        mmap.put("boxDetail",electricBoxItemService.findById(id));
        return prefix + "/edit";
    }

    //打印
    @RequestMapping("print")
    public String print(@RequestParam String ids, Model model) {

        //System.out.println(ids);
        List<ElectricBoxDetail> byIds = electricBoxItemService.findByIds(ids);
        model.addAttribute("byids", byIds);


        return prefix + "print";
    }


    @PostMapping("fetchBoxList")
    @ResponseBody
    public String fetchBoxList(@RequestBody ElectricBox electricBox) {

        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmdd");
        Gson gson = new Gson();
        ElectricResult electricResult = new ElectricResult();

        log.info(gson.toJson(electricBox));

        try {
//            electricBox = gson.fromJson(strBoxInfo, ElectricBox.class);
            electricResult.setTorrNumber(electricBox.getHEAD().getTorr());
            electricResult.setResult("0");
            electricResult.setErrorDesc("Success:\"\"");
            List<ElectricBoxDetail> item = electricBox.getITEM();
            for (ElectricBoxDetail b : item) {
                ElectricBoxDetail torrNumber = electricBoxItemService.findBy("TorrNumber", b.getTorrNumber());
                if (torrNumber.getTorrNumber() != null) {
                    electricBoxItemService.update(b);
                } else {
                    electricBoxItemService.save(b);
                }

            }


        } catch (Exception e) {
            electricResult.setErrorDesc("Fail:" + e.getMessage());
            electricResult.setResult("-1");
        }


        String result = gson.toJson(electricResult);
        return result;
    }
}

